package netty.http.xml.client;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import netty.http.xml.codec.HttpXmlRequest;
import netty.http.xml.codec.HttpXmlResponse;
import netty.http.xml.pojo.OrderFactory;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2021-10-28 14:31:00
 */
@Slf4j
public class HttpXmlClientHandler extends SimpleChannelInboundHandler<HttpXmlResponse> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String jsonStr = JSON.toJSONString(OrderFactory.create(123));
        HttpXmlRequest request = new HttpXmlRequest(null, jsonStr);
        ctx.writeAndFlush(request);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpXmlResponse httpXmlResponse) throws Exception {
        log.info("The client receive response of http header is : " + httpXmlResponse.getHttpResponse().headers().names());
        log.info("The client receive response of http body is : " + httpXmlResponse.getResult());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
